package mo.leetcode_hot;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class L347 {

    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> num2count = new HashMap<>();
        for (int num : nums) {
            if (num2count.get(num) == null) {
                num2count.put(num, 1);
            } else {
                int count = num2count.get(num);
                count++;
                num2count.put(num, count);
            }
        }
        int max = 0;
        for (Map.Entry<Integer, Integer> entry : num2count.entrySet()) {
            Integer value = entry.getValue();
            max = Math.max(max, value);
        }
        int[] res = new int[k];
        while (k > 0) {
            for (Map.Entry<Integer, Integer> entry : num2count.entrySet()) {
                Integer value = entry.getValue();
                if (value == max) {
                    res[k-1] = entry.getKey();
                    k--;
                }
            }
            max--;
        }
        return res;
    }

    public static void main(String[] args) {
        L347 test = new L347();
        System.out.println(Arrays.toString(test.topKFrequent(new int[]{1, 1, 1, 2, 2, 3}, 2)));
    }

}
